import pytest
import pymysql
import json
import os
from pathlib import Path


from api.shop_api import Api
from common.assert_tools import common_assert
from common.read_json_file import read_json_data
from config.config import admin_login


class TestShopAddItem(object):
    json_path = os.path.join(Path(__file__).parent.parent, "data", "add_item_data.json")
    data = read_json_data(json_path)
    
    def setup_class(self):
        """测试类开始前获取管理员token"""
        print("\n开始获取管理员登录token...")
        resp = Api.manager_login(admin_login)
        
        if resp.status_code == 200 and resp.json().get("code") == "0":
            self.token = resp.json()["data"]["token"]
            print(f"成功获取管理员token: {self.token[:20]}...")
        else:
            pytest.fail(f"管理员登录失败: {resp.json()}")
    
    @pytest.mark.parametrize("desc,req_data,status_code,code,msg", data)
    def test01_add_item(self, desc, req_data, status_code, code, msg):
        """测试添加商品接口"""
        resp = Api.add_item(req_data, self.token)
        
        # 格式化输出
        print("\n" + "=" * 80)
        print(f"测试用例: {desc}")
        print(f"请求数据: {req_data}")
        print(f"响应结果: {resp.json()}")
        print(f"期望结果: HTTP状态码={status_code}, code={code}, msg={msg}")
        print("=" * 80)
        
        common_assert(resp, status_code, code, msg)
    
    def teardown_class(self):
        """测试类结束后自动清理测试数据"""
        print("\n开始清理测试数据...")
        
        # 连接数据库
        conn = pymysql.connect(host='127.0.0.1', port=3306, user='root',
                             password='123456', database='tshop', charset='utf8')
        cursor = conn.cursor()
        
        try:
            # 读取测试商品标题并删除
            with open('data/add_item_data.json', 'r', encoding='utf-8') as f:
                item_titles = [item['req_data']['title'] 
                             for item in json.load(f) 
                             if item['req_data'].get('title')]
            
            deleted_count = 0
            for title in item_titles:
                cursor.execute("DELETE FROM tshop.item WHERE title = %s", (title,))
                if cursor.rowcount > 0:
                    deleted_count += 1
                    print(f"已删除测试商品: {title}")
            
            conn.commit()
            print(f"清理完成！共删除 {deleted_count} 个测试商品")
            
        except Exception as e:
            print(f"清理失败: {e}")
            conn.rollback()
        finally:
            cursor.close()
            conn.close() 